<?php
error_reporting(E_ALL ^ E_NOTICE);
class pagerank{
	private static $instance;

	function stringToNumber($string,$check,$magic) {
		$int32 = 4294967296;  // 2^32
	    $length = strlen($string);
	    for ($i = 0; $i < $length; $i++) {
	        $check *= $magic;
	        if($check >= $int32) {
	            $check = ($check - $int32 * (int) ($check / $int32));
	            //if the check less than -2^31
	            $check = ($check < -($int32 / 2)) ? ($check + $int32) : $check;
	        }
	        $check += ord($string{$i}); 
	    }
	    return $check;
	}

	function createHash($string) {
		$check1 = $this->stringToNumber($string, 0x1505, 0x21);
	    $check2 = $this->stringToNumber($string, 0, 0x1003F);
	
		$factor = 4;
		$halfFactor = $factor/2;

	    $check1 >>= $halfFactor;
	    $check1 = (($check1 >> $factor) & 0x3FFFFC0 ) | ($check1 & 0x3F);
	    $check1 = (($check1 >> $factor) & 0x3FFC00 ) | ($check1 & 0x3FF);
	    $check1 = (($check1 >> $factor) & 0x3C000 ) | ($check1 & 0x3FFF);	

	    $calc1 = (((($check1 & 0x3C0) << $factor) | ($check1 & 0x3C)) << $halfFactor ) | ($check2 & 0xF0F );
	    $calc2 = (((($check1 & 0xFFFFC000) << $factor) | ($check1 & 0x3C00)) << 0xA) | ($check2 & 0xF0F0000 );

	    return ($calc1 | $calc2);
	}
	
	// Create checksum for hash
	function checkHash($hashNumber){
	    $check = 0;
		$flag = 0;

		$hashString = sprintf('%u', $hashNumber) ;
		$length = strlen($hashString);

		for ($i = $length - 1;  $i >= 0;  $i --) {
			$r = $hashString{$i};
			if(1 === ($flag % 2)) {			  
				$r += $r;	 
				$r = (int)($r / 10) + ($r % 10);
			}
			$check += $r;
			$flag ++;	
		}

		$check %= 10;
		if(0 !== $check) {
			$check = 10 - $check;
			if(1 === ($flag % 2) ) {
				if(1 === ($check % 2)) {
					$check += 9;
				}
				$check >>= 1;
			}
		}

		return '7'.$check.$hashString;
	}
	
	function check($page) {
		$options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => "Mozilla/5.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)");
		
		$ch = curl_init("toolbarqueries.google.com/tbr?client=navclient-auto&ch=".$this->checkHash($this->createHash($page))."&features=Rank&q=info:".$page."&num=100&filter=0");
			curl_setopt_array($ch, $options);
			$content = curl_exec($ch);
			curl_close($ch);
		
		if(!$content){
			return -1;
		}
		preg_match_all("#:(\d+)#",$content,$m);
		
		return $m[1][1];
	}
	// Constructor
	public static function getRank($page) {
		if(!isset(self::$instance)){
			self::$instance = new self();
		}
		return self::$instance->check($page);
	}
}

class icx{
	var $content;
	
	function get_seomoz($urls=array()){
		/*max 10 urls - http://apiwiki.seomoz.org/categories/api-reference*/
		for($i=0;$i<count($urls);$i++){
			$urls[$i]=preg_replace("#(http|https):\/\/#","",$urls[$i]);
		}
		/*
		member-855e32353e
		ae88ba355a02f8e6a52f42e966e32371
		*/
		$accessID = "member-f5201cb1bf";
		$secretKey = "d82c1ee346b35d02da453ca0681a1c6d";
		$expires = time() + 300;
		
		$stringToSign = $accessID."\n".$expires;
		$binarySignature = hash_hmac('sha1', $stringToSign, $secretKey, true);
		
		$urlSafeSignature = urlencode(base64_encode($binarySignature));

		//ext links+ links + mozrank + subd mozrank (32768) + pa + da
		$cols=103079233568;
		//32+2048+16384+34359738368+68719476736
		
		// Put it all together and you get your request URL.
		$requestUrl = "http://lsapi.seomoz.com/linkscape/url-metrics/?Cols=".$cols."&AccessID=".$accessID."&Expires=".$expires."&Signature=".$urlSafeSignature;
		$encodedDomains = json_encode($urls);
		$options = array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_POSTFIELDS     => $encodedDomains
			);

		$ch = curl_init($requestUrl);
		curl_setopt_array($ch, $options);
		$content = curl_exec($ch);
		curl_close($ch);
		$contents = json_decode($content);
		
		/*external ueid
		links - uid
		mozrank - umrp (1 - 10)
		subdomain mozrank - fmrp
		pa - upa
		da - pda
		*/
		
		return $contents;
	}
	function get_results($kw,$pag){
		/*init without errors*/
		$data['error']=false;
		
		$options = array(CURLOPT_RETURNTRANSFER => true, CURLOPT_USERAGENT => "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22");
		if(substr_count($kw,' ')>0){
			$kws=str_replace(' ','+',$kw);
		}else{
			$kws=$kw;
		}
		
		$url="http://www.google.com/search?q=".$kws."&gl=us&hl=en&pws=0";
		$ch = curl_init($url);
		curl_setopt_array($ch, $options);
		
		$this->content = curl_exec($ch);
		/*
		$fp = fopen('zz.txt', 'w');
		fwrite($fp, $this->content);
		fclose($fp);
		*/
		if(preg_match('#302 Moved#',$this->content)){
			preg_match('#="(.*)">here#', $this->content,$m);
			//echo urldecode($m[1]);
			//var_dump($m[1]);
			
			
			$ch = curl_init($m[1]);
			curl_setopt_array($ch, $options);
			$res = curl_exec($ch);
			/*Intrati in pagina noua*/
			preg_match('#id=(\d+)#',$res,$img);
			
			echo '
			<head>
			<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
			<script>
			function snd(){
			var txt=$("#txt").val();
			var url="'.urldecode($m[1]).'";
			var id="'.$img[1].'";
				$.post("ajax.php?page=captcha", { "txt": txt,"url":url,"id":id},
					function(data){
						$(".container-fluid").html("<center>"+data.message+"</center>");
					}, "json");
			
			}
			</script>
			</head>
			<body>
			<br><img src="http://www.google.com/sorry/image?id='.$img[1].'">
			<input type="text" id="txt" />
			<input type="button" onclick="snd();" value="Send">
			</body>
			';
			
			//var_dump($res);
			curl_close($ch);
			
			return $data['error']=true;
			//var_dump($res);
			/*Fetch google img*/
		}
		
		curl_close($ch);
		if($data['error']){
			die();
		}
		/*
		Old url: @<h3\s*class="r">\s*<a[^<>]*href="\/url\?q=([^<>]*)&amp;sa=U(.*)"[^<>]*>(.*)</a>\s*</h3>@siU
		*/
		preg_match_all('@<h3\s*class="r">\s*<a[^<>]*href="([^<>]*)"[^<>]*>(.*)</a>\s*</h3>@siU',$this->content,$m);
		
		if(!$m[1]){
			return $data['error']=true;
		}
		
		for($i=0;$i<count($m[1]);$i++){
			$data['url'][$i]=urldecode($m[1][$i]);
			$data['title'][$i]=strip_tags($m[2][$i]);
		}

		return $data;
	}
	/*Get all social*/
	function get_social($url){
		$url="http://api.sharedcount.com/?url=".rawurlencode($url);
		$options = array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER, false
		);
		
		$ch = curl_init($url);
		curl_setopt_array($ch, $options);
		$content = curl_exec($ch);
		curl_close($ch);
		$counts = json_decode($content, true);
		
		$data['twitter']=$counts["Twitter"];
		$data["fb_like"]=$counts["Facebook"]["like_count"];
		$data["fb_share"]=$counts["Facebook"]["share_count"];
		$data["delicious"]=$counts["Twitter"];
		$data["stumble"]=$counts["StumbleUpon"];
		$data["reddit"]=$counts["Reddit"];
		$data["plus"]=$counts["GooglePlusOne"];
		$data["pinterest"]=$counts["Pinterest"];
		$data["linkedin"]=$counts["LinkedIn"];
		
		return $data;
	}
	
	
	
	/*Get pagerank*/
	function get_pr($url){
		$options = array(
			CURLOPT_RETURNTRANSFER => true,
			CURLOPT_SSL_VERIFYPEER, false
		);
		$ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "https://tools.digitalpoint.com/pagerank?url=".urlencode($url));
		curl_setopt_array($ch, $options);
		$content = curl_exec($ch);
		curl_close($ch);
		
		preg_match('/<dd style="font-weight:bold">(.*)<\/dd>/i', $content, $m);
		return $m[1];
	}
	
	
	
	/*Old way*/
	function get_plus($url){
		//get google plus share count php
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, "https://plusone.google.com/_/+1/fastbutton?url=".urlencode($url));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        $html = curl_exec ($curl);
        curl_close ($curl);
		
        $doc = new DOMDocument();
        $doc->loadHTML($html);
        $counter=$doc->getElementById('aggregateCount');
        return $counter->nodeValue;
    }
	
	/*function __construct($keywordsGot,$pageNum)
	{	
		$options = array(
			CURLOPT_RETURNTRANSFER => true
		//	CURLOPT_POSTFIELDS     => $encodedDomains
			);

		if(substr_count($keywordsGot,' ')>0){
			$keywords=str_replace(' ','+',$keywordsGot);
		}else{
			$keywords=$keywordsGot;
		}
		
		if($pageNum==0){
			$url="http://www.google.com/search?q=".$keywords."&gl=us&hl=en";
			$ch = curl_init($url);
			curl_setopt_array($ch, $options);
			$this->content = curl_exec($ch);
			curl_close($ch);	
		}
		else
		{
			$index=($pageNum*10);
			$url="http://www.google.com/search?q=".$keywords."&start=".$index."&gl=us&hl=en";
			$ch = curl_init($url);
			curl_setopt_array($ch, $options);
			$this->content = curl_exec($ch);
			curl_close($ch);
		}		
			
				
	}
	*/
	
	
}
?>